#include "UdpServer.hpp"

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        exit(0);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    int socket = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(socket < 0)
    {
        LOG(FATAL, "client create socket error\n");
        exit(1);
    }
   
    struct sockaddr_in server;
    // socklen_t len = sizeof(server);
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while (true)
    {
        std::cout << "Please Enter:> ";
        std::string msg;
        std::getline(std::cin, msg);

        int n = ::sendto(socket, msg.c_str(), msg.size(), 0, (struct sockaddr*)&server, sizeof(server));
        if(n > 0)
        {
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            char buffer[1024];
            int m = ::recvfrom(socket, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&tmp, &len);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cerr << "recvfrom error" << std::endl;
                break;
            }
        }
        else
        {
            std::cerr << "sendto error" << std::endl;
            break;
        }
    }

    ::close(socket);
    return 0;
}